var mongoose=require('mongoose');
var config=require('../config');
var con=config.config;
var mongodb = require('mongodb');
var Schema=mongoose.Schema;
var Goods=require('./goods');
var db=mongoose.createConnection(config.db_url);
var _ = require("underscore");
db.on('error',function(error){
    db.close();
    console.log(error);
});

db.on('close', function () {
    db.open(config.db_url);
    console.log("重新连接mongo");
});
db.model('Goods',Goods.goodsSchema);
var doorSchema = new Schema({
    index: Number,
    empty: Boolean,
    password: String,
    opentime: Number,
    use:{type:Number,default:0},
    gid:{type:Schema.Types.ObjectId,ref:'Goods'},
    owner: String //user or wechat's openid
});
var boxSchema = new Schema({
    box_id: String, // the box id
    code_layout:String, //贴码位置，0:左,1:右
    doors_num:Number, //门的数量，只能为偶数
    box_layout:String, //箱子布局
    doors: [doorSchema],
    addr:String,
    lat:String,
    lng:String,
    addrDescribe:String

});
var Box = db.model("Box", boxSchema);

Box.prototype.findBoxById=function (boxid,callback){
    Box.find({box_id:boxid}, function(err, datas){
        return callback(datas);
    });
}

Box.prototype.findBoxesById=function (opt,callback){
    Box.find(opt, function(err, datas){
        return callback(datas);
    });
}

Box.prototype.findByBoxId = function(boxid, callback) {
    Box.findOne({
        box_id: boxid
    }, function(err, box) {
        var data = [];
        _.each(box.doors, function(door, index, list) {
            data.push({
                index: door.index,
                empty: door.empty,
                password: door.password,
                opentime: door.opentime,
                owner: door.owner //user or wechat's openid
            });
        });
        callback(data);
    });
}
Box.prototype.findByBoxId2 = function(boxid, callback) {
    var query=Box.findOne({box_id:boxid}).populate('doors.gid')
    query.exec(function(err,box){
        if(box){
            var layout = getGridLayout(box.box_layout);
            box.layout=layout
        }
        callback(box);
    })
//    Box.findOne({
//        box_id: boxid
//    }, function(err, box) {
//
//        if(box){
//            var layout = getGridLayout(box.box_layout);
//            box.layout=layout
//        }
//        callback(box);
//    });
}

Box.prototype.updateByBoxidAndIndex = function(boxid, index, callback) {
    Box.update({
        "box_id": boxid,
        "doors.index": index
    }, {
        "doors.$.empty": true,
        "doors.$.password": "",
        "doors.$.opentime": "",
        "doors.$.owner": ""
    }, function(err) {
        if (err) {
        }
        callback(boxid);
    });
}
Box.prototype.updateDoorUse = function(boxid, index, use,callback) {
    Box.update({
        "box_id": boxid,
        "doors.index": index
    }, {
        "doors.$.use": use
    }, function(err) {
        if (err) {
        }
        callback(boxid);
    });
}
Box.prototype.updateOpt = function(opt1,opt2,callback) {
    Box.update(opt1
    , opt2, function(err,data) {
        if (err) {
        }
        callback(err,data);
    });
}
Box.prototype.updateAddr = function(boxid,options,callback) {
    Box.update({
        "box_id": boxid
    }, options, function(err) {
        if (err) {
        }
        callback(boxid);
    });
}
Box.prototype.updateDoorById=function(boxid,doors,callback){
    Box.update({box_id:boxid},{
        doors:doors
    },function(err){
        return callback(err);
    });
}

Box.prototype.updateCodeById=function(boxid,code_layout,callback){
    Box.update({box_id:boxid},{"code_layout":code_layout},function(err){
        return callback(err);
    });
}

Box.prototype.updateDoorNumById=function(boxid,doors,door_num,box_layout,callback){
    Box.update({box_id:boxid},{doors:doors,doors_num:door_num,box_layout:box_layout},function(err){
        return callback(err);
    });
}

Box.prototype.updateAllById=function(boxid,doors,door_num,box_layout,code_layout,callback){
    Box.update({box_id:boxid},{doors:doors,doors_num:door_num,box_layout:box_layout,code_layout:code_layout},function(err){
        return callback(err);
    });
}

Box.prototype.findForPage=function(obj,callback){
    var q=obj.search||{};                                       //查询条件
    var col=obj.columns||{};                                    //返回字段
    var query=Box.find(q,col).skip(obj.page.skipFrom).limit(obj.page.limit).populate('doors.gid');

    query.exec(function(err, datas) {
        if (err) {
            callback(err, null, null);
        } else {
            Box.count(q, function(err, count) {
                if (err) {
                    callback(err, null, null);
                } else {
                    var pageCount = Math.ceil(count / obj.page.limit);
                    datas.forEach(function(data,index){
                        var layout = getGridLayout(data.box_layout);
                        data._doc.layout=layout
                    })
                    console.log(datas)
                    callback(null,count,pageCount, datas);
                }
            });
        }
    });
}
function getGridLayout(boxLayout){
    var layout;
    switch (boxLayout){
        case "一行两列":
            layout = {
                row:1,
                column:2
            };
            break;
        case "两行一列":
            layout = {
                row:2,
                column:1
            };
            break;
        case "两行两列":
            layout = {
                row:2,
                column:2
            };
            break;
        case "一行四列":
            layout = {
                row:1,
                column:4
            };
            break;
        case "四行一列":
            layout = {
                row:4,
                column:1
            };
            break;
        case "三行两列":
            layout = {
                row:3,
                column:2
            };
            break;
        case "两行三列":
            layout = {
                row:2,
                column:3
            };
            break;
        case "四行两列":
            layout = {
                row:4,
                column:2
            };
            break;
        case "两行四列":
            layout = {
                row:2,
                column:4
            };
            break;
        case "两行五列":
            layout = {
                row:2,
                column:5
            };
            break;
        case "五行两列":
            layout = {
                row:5,
                column:2
            };
            break;
        case "三行四列":
            layout = {
                row:3,
                column:4
            };
            break;
        case "四行三列":
            layout = {
                row:4,
                column:3
            };
            break;
    }
    return layout;

}
module.exports = Box;